package com.css.dzj.dzjap.modules.info.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.css.aq.server.service.BaseService;
import com.css.dzj.dzjap.common.audit.service.SysAuditService;
import com.css.dzj.dzjap.common.util.BeanUtil;
import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.userinfo.UserInfoService;
import com.css.dzj.dzjap.modules.apunit.entity.ApUnitEntity;
import com.css.dzj.dzjap.modules.construnit.entity.ConstructionUnitEntity;
import com.css.dzj.dzjap.modules.info.service.ConstrService;
import com.css.dzj.dzjap.modules.info.service.EvalUnitService;
import com.css.dzj.dzjap.modules.info.vo.ApJsVo;
import com.css.dzj.dzjap.modules.info.vo.EvalInfoVo;
import com.css.dzj.dzjap.modules.todolist.entity.ApTodoEntity;
import com.css.dzj.dzjap.modules.todolist.service.ApTodoService;
import com.querydsl.core.QueryResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 安平单位
 *
 * @author liangxingguo
 */
@RestController
@RequestMapping("/evalunit")
@PropertySource(value = "classpath:base.properties")
public class EvalUnitController {

    @Autowired
    EvalUnitService evalUnitService;
    @Autowired
    ApTodoService apTodoService;
    @Value("${SAVE_USER}")
    String SAVE_USER;
    @Value("${BASE_URL}")
    private String BASE_URL;
    @Autowired
    private SysAuditService sysAuditService;

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private  ConstrService constrService;

    /**
     * 分页查询评价单位
     *
     * @param pageNo
     * @param pageSize
     * @param unitName 单位名称
     * @param uniscid  统一社会信用代码
     * @param spStatus 审批状态  1:未审批 2：审批不通过3：审批通过
     * @param spPerson 审批人
     * @return
     */
    @GetMapping("/listpage")
    public R getPageEval(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                         @RequestParam(name = "unitName", required = false) String unitName,
                         @RequestParam(name = "uniscid", required = false) String uniscid,
                         @RequestParam(name = "startTime", required = false) String startTime,
                         @RequestParam(name = "endTime", required = false) String endTime,
                         @RequestParam(name = "spStatus", required = false) String spStatus,
                         @RequestParam(name = "spPerson", required = false) String spPerson,
                         @RequestParam(name = "sbStatus", required = false) String sbStatus,
                         HttpServletRequest request) {
        String s = "";
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            QueryResults page = evalUnitService.getPage(pageRequest, unitName, uniscid, startTime, endTime, spStatus, spPerson, sbStatus, request);
            s = JSON.toJSONString(page);
            sysAuditService.saveSuccessAudit("查询成功", Constant.EVALUNIT,Constant.PT,Constant.PAGE,s,request);
            return R.ok().put("page", page);
        } catch (Exception e) {
            e.printStackTrace();
            sysAuditService.saveFailAudit("查询失败",Constant.TODO,Constant.PT,Constant.PAGE,s,e,request);
            return  R.error("操作失败!");
        }
    }


    /**
     * 分页查询评价单位
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/listeval")
    public R getEval(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                     @RequestParam(name = "enterpriseName", required = false) String enterpriseName,
                     @RequestParam(name = "enterpriseIdNumber", required = false) String enterpriseIdNumber) {
        String s = "";
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            QueryResults page = evalUnitService.getPageEval(pageRequest, enterpriseName, enterpriseIdNumber);
            List<ApUnitEntity> list = page.getResults();
            List<EvalInfoVo> evalInfoVoList = new ArrayList<>();
            for (ApUnitEntity apUnitEntity : list) {
                EvalInfoVo evalInfoVo = new EvalInfoVo();
                evalInfoVo.setEnterpriseName(apUnitEntity.getUnitName());
                evalInfoVo.setEnterpriseIdNumber(apUnitEntity.getUniscid());
                evalInfoVo.setEnterpriseIdType(apUnitEntity.getQyUnitType());
                evalInfoVo.setLegalMan(apUnitEntity.getLegalMan());
                evalInfoVo.setRecordUnitUser(apUnitEntity.getLinkMan());
                evalInfoVo.setRecordUnitPhone(apUnitEntity.getLinkTel());
                evalInfoVoList.add(evalInfoVo);
            }
            QueryResults queryResults = new QueryResults(evalInfoVoList, page.getTotal(), page.getOffset(), page.getTotal());
            s = JSON.toJSONString(queryResults);
            sysAuditService.saveSuccessAudit("查询成功", Constant.EVALUNIT, Constant.PT, Constant.PAGE, s, request);
            return R.ok().put("data", queryResults);
        }catch (Exception e){
            e.printStackTrace();
            s = JSON.toJSONString(null);
            sysAuditService.saveFailAudit("查询失败", Constant.EVALUNIT, Constant.PT, Constant.PAGE, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /***
     *逻辑删除评价单位
     * @param id
     * @return
     */
    @PostMapping("/delConstr/{id}")
    public R delEval(@PathVariable String id) {
        String  s = "";
        try {
            boolean flag = evalUnitService.delEval(id);
            if (flag) {
                s = JSON.toJSONString(id);
                sysAuditService.saveSuccessAudit("删除成功", Constant.EVALUNIT, Constant.PT, Constant.DEL, s, request);
                return R.ok("删除成功");
            }
            return R.error("删除失败");
        }catch (Exception e){
            e.printStackTrace();
            s = JSON.toJSONString(null);
            sysAuditService.saveFailAudit("删除失败", Constant.EVALUNIT, Constant.YZ, Constant.DEL, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /***
     * 根据Id查找评价单位
     * @param id
     * @return
     */
    @PostMapping("/findbyid/{id}")
    public R findById(@PathVariable String id) {
        String s = "";
        try{
            if (!StringUtils.isEmpty(id)) {
                ApUnitEntity apUnitEntity = evalUnitService.findById(id);
                s = JSON.toJSONString(apUnitEntity);
                sysAuditService.saveSuccessAudit("删除成功", Constant.EVALUNIT, Constant.PT, Constant.DEL, s, request);
                return R.ok().put("apUnitEntity", apUnitEntity);
            } else {
                return R.error("Id为空");
            }
        }catch (Exception e){
            e.printStackTrace();
            s = JSON.toJSONString(null);
            sysAuditService.saveFailAudit("删除失败", Constant.EVALUNIT, Constant.YZ, Constant.DEL, s, e, request);
            return R.error(e.getMessage());
        }

    }

    /***
     * 上报评价单位
     * @param apUnitEntity
     * @return
     */
    @PostMapping("/updatebyid/{sbstatus}")
    public R upadateById(@PathVariable String sbstatus, @RequestBody ApUnitEntity apUnitEntity) {
        String s = "";
        try{
            ApUnitEntity apUnitEntity1 = evalUnitService.findById(apUnitEntity.getId());
            if (!StringUtils.isEmpty(apUnitEntity1)) {
                if ("3".equals(apUnitEntity.getSpStatus())) {
                    BeanUtil.copyBeanNotEmptyToBean(apUnitEntity, apUnitEntity1);
                    ApTodoEntity apTodoEntity = apTodoService.findByLinkId(apUnitEntity.getId());
                    if (!StringUtils.isEmpty(apTodoEntity)) {
                        apTodoEntity.setStatus(apUnitEntity.getSpStatus());
                        apTodoService.update(apTodoEntity);
                    }
                    apUnitEntity1.setUpdateTime(new Date());
                    apUnitEntity1.setSpTime(new Date());
                    apUnitEntity1.setSbStatus(sbstatus);
                    evalUnitService.update(apUnitEntity1);
                    s = JSON.toJSONString(apUnitEntity1);
                    sysAuditService.saveSuccessAudit("更新成功", Constant.EVALUNIT, Constant.PT, Constant.UPDATE, s, request);
                    return R.ok();
                } else {
                    return R.error("审批未通过不能上报");
                }
            } else {
                return R.error("操作失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            s = JSON.toJSONString(null);
            sysAuditService.saveFailAudit("操作失败", Constant.EVALUNIT, Constant.YZ, Constant.UPDATE, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /***
     * 审批
     * @param apUnitEntity
     * @return
     */
    @PostMapping("/update")
    public R upadateSp(@RequestBody ApUnitEntity apUnitEntity) {
        String s = "";
        try{
        Map<String, String> map = new HashMap();
        ApUnitEntity apUnitEntity1 = evalUnitService.findById(apUnitEntity.getId());
        if (!StringUtils.isEmpty(apUnitEntity1)) {
            BeanUtil.copyBeanNotEmptyToBean(apUnitEntity, apUnitEntity1);
            ApTodoEntity apTodoEntity = apTodoService.findByLinkId(apUnitEntity.getId());
            if (!StringUtils.isEmpty(apTodoEntity)) {
                apTodoEntity.setStatus(Constant.STATUSYB);
                apTodoService.update(apTodoEntity);
            }
            if (Constant.CHECK_RESULT_YES.equals(apUnitEntity1.getCheckResult())) {
                String url = BASE_URL + SAVE_USER;
                if (!StringUtils.isEmpty(apUnitEntity.getUserName())) {
                    String loginName = apUnitEntity.getUserName();
                    map.put("loginName", loginName);
                } else {
                    return R.error("用户名不能为空");
                }

                if (!StringUtils.isEmpty(apUnitEntity.getPassword())) {
                    String password = apUnitEntity.getPassword();
                    map.put("password", password);
                } else {
                    return R.error("密码不能为空");
                }
                String anping = "anping";
                /*map.put("userSystem",anping);
                HttpClientUtil.doPost(url,map);*/
                //baseService.add(apUnitEntity.getUserName(), anping, apUnitEntity.getPassword());
                // 新base注册
                userInfoService.register(apUnitEntity.getUserName(), apUnitEntity.getPassword(),anping, request);
            }
            if (Constant.CHECK_RESULT_YES.equals(apUnitEntity1.getCheckResult())) {
                apUnitEntity1.setSpStatus(Constant.CHECK_STATUS3);
            }
            if (Constant.CHECK_RESULT_NO.equals(apUnitEntity1.getCheckResult())) {
                apUnitEntity1.setSpStatus(Constant.CHECK_STATUS2);
            }
            apUnitEntity1.setCheckResult(apUnitEntity.getCheckResult());
            apUnitEntity1.setUpdateTime(new Date());
            Date date = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = null;
            try {
                date1 = sf.parse(sf.format(date));
                System.out.println(date1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            apUnitEntity1.setSpTime(date1);
            evalUnitService.update(apUnitEntity1);
            s = JSON.toJSONString(apUnitEntity1);
            sysAuditService.saveSuccessAudit("更新成功", Constant.EVALUNIT,Constant.PT,Constant.UPDATE,s,request);
            return R.ok();
        } else {
            return R.error("操作失败");
        }
        }catch (Exception e){
            e.printStackTrace();
            s = JSON.toJSONString(null);
            sysAuditService.saveFailAudit("更新失败", Constant.EVALUNIT, Constant.YZ, Constant.UPDATE, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /***
     * 获取安评单位数量
     * @return
     */
    @GetMapping("/countunit")
    public R countunit() {
        HashMap count = evalUnitService.getCount();
        return R.ok().put("count", count);
    }

    /***
     * 获取安评单位数量根据年度
     * @return
     */
    @GetMapping("/countunityear")
    public R countunitByYear(String year) {
        HashMap count = evalUnitService.getCountByYear(year);
        return R.ok().put("count", count);
    }

    /*********************************************** 门户调用接口 start *********************************************************************/

    /**
     * 门户：分页查询评价单位，不需要判断用户
     *
     * @param pageNo
     * @param pageSize
     * @param unitName
     * @param uniscid
     * @param startTime
     * @param endTime
     * @param spStatus
     * @param spPerson
     * @param sbStatus
     * @return
     */
    @GetMapping("/getPage")
    public QueryResults getEvalPage(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                                    @RequestParam(name = "unitName", required = false) String unitName,
                                    @RequestParam(name = "uniscid", required = false) String uniscid,
                                    @RequestParam(name = "startTime", required = false) String startTime,
                                    @RequestParam(name = "endTime", required = false) String endTime,
                                    @RequestParam(name = "spStatus", required = false) String spStatus,
                                    @RequestParam(name = "spPerson", required = false) String spPerson,
                                    @RequestParam(name = "sbStatus", required = false) String sbStatus) {
        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
        QueryResults page = evalUnitService.getPage(pageRequest, unitName, uniscid, startTime, endTime, spStatus, spPerson, sbStatus);
        return page;
    }

    @GetMapping("/getList")
    public List getEvalList(@RequestParam(name = "unitName", required = false) String unitName,
                            @RequestParam(name = "uniscid", required = false) String uniscid,
                            @RequestParam(name = "startTime", required = false) String startTime,
                            @RequestParam(name = "endTime", required = false) String endTime,
                            @RequestParam(name = "spStatus", required = false) String spStatus,
                            @RequestParam(name = "spPerson", required = false) String spPerson,
                            @RequestParam(name = "sbStatus", required = false) String sbStatus) {
        List<ApUnitEntity> list = evalUnitService.queryByParams(unitName, uniscid, startTime, endTime, spStatus, spPerson, sbStatus);
        return list;
    }

    /**
     * 根据ids(逗号分隔)查询List数据
     *
     * @param ids
     * @return
     */
    @GetMapping("/getListByIds")
    public List exportToExcel(@RequestParam String ids) {
        List<ApUnitEntity> list = evalUnitService.queryByIds(ids);
        return list;
    }

    /**
     * 获取总数
     *
     * @return
     */
    @GetMapping("/getTotalCount")
    public Integer getTotalCount() {
        Integer count = evalUnitService.getTotalCount();
        return count;
    }
    /*********************************************** 门户调用接口 end *********************************************************************/

   /* @GetMapping("/getPageLHCx")
    public QueryResults getPageLHCx(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                            @RequestParam(name = "unitName", required = false) String unitName,
                            @RequestParam(name = "uniscid", required = false) String uniscid) {
        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
        QueryResults<ApUnitEntity> alist = evalUnitService.getPageLHCx(pageRequest,unitName,uniscid,pageSize,pageNo);

           return alist;
    }*/

}
